package com.itheima.threadsafetylock;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {

    private String cardId;      //卡号
    private double money;       //账户余额

    private final Lock lk = new ReentrantLock();    //加final，保护锁对象，防止被篡改

    public void drawMoney(double money) {

        //拿到取钱人的名字
        String name = Thread.currentThread().getName();
        System.out.println(name + "取钱中...");

        lk.lock();      //上锁

        try {
            //先判断余额是否足够
            if (this.money >= money) {
                //余额足够，取钱
                System.out.println(name + "取钱成功，本次取钱金额为：" + money);
                //更新余额
                this.money -= money;
                System.out.println(name + "本次取钱后，余额为：" + this.money);
            } else {
                //余额不足，取钱失败
                System.out.println(name + "取钱失败，余额不足！");
                System.out.println("当前余额为：" + this.money);
            }
        } finally {
            //放到finally中，保证锁一定被释放
            lk.unlock();        //解锁
        }

    }
}
